package services

import (
	"backend/log"
	"backend/models"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

type PermissionServices struct {
	db *gorm.DB
}

func NewPermissionServices(db *gorm.DB) *PermissionServices {
	return &PermissionServices{db: db}
}

func (s *PermissionServices) Create(m *models.Permission) error {
	if err := s.db.Create(m).Error; err != nil {
		return err
	}

	// 确保关联关系被正确处理
	if m.MenuId > 0 {
		// 更新菜单的权限关系
		var menu models.Menu
		if err := s.db.First(&menu, m.MenuId).Error; err != nil {
			return err
		}

		// 手动添加权限到菜单的权限列表
		if err := s.db.Model(&menu).Association("Permissions").Append(m); err != nil {
			return err
		}
	}

	return nil

}

func (s *PermissionServices) Update(m *models.Permission) error {
	return s.db.Save(m).Error
}

func (s *PermissionServices) Delete(uuid string) error {
	return s.db.Where("id = ?", uuid).Delete(&models.Permission{}).Error
}

func (s *PermissionServices) GetPermissionList(q *models.PageInfo, m *models.Permission) ([]*models.Permission, int64, error) {
	var permissions []*models.Permission
	var total int64

	query := s.db.Model(models.Permission{}).Preload("Menu")
	if m.Name != "" {
		query = query.Where("name = ?", m.Name)
	}
	if m.Action != "" {
		query = query.Where("action = ?", m.Action)
	}
	if m.Path != "" {
		query = query.Where("path = ?", m.Path)
	}
	if m.Method != "" {
		query = query.Where("method = ?", m.Method)
	}
	if m.MenuId >= 1 {
		query = query.Where("menu_id = ?", m.MenuId)
	}

	// 获取符合条件的总数
	if err := query.Count(&total).Error; err != nil {
		log.Logger.Error("获取权限总数失败", zap.Error(err))
		return nil, 0, err
	}

	result := query.Order("created_at DESC").Limit(q.Size).Offset((q.Page - 1) * q.Size).Find(&permissions)
	if result.Error != nil {
		log.Logger.Error("获取权限失败", zap.Error(result.Error))
		return nil, 0, result.Error
	}
	return permissions, total, nil
}
